import 'package:flutter_mode/zyj/model/user.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
class DbManager{
  DbManager._internal();
  static DbManager singleton = DbManager._internal();
  //获取路径
  Future<String> get _dbPath async {
    var directory = await getApplicationDocumentsDirectory();
    String path = directory.path + "test.db";
    return path;
  }

  //创建数据库
  Future<Database> get _localFile async {
    final path = await _dbPath;
    var db = openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
          await db.execute(
              "CREATE TABLE user (id INTEGER PRIMARY KEY, accountName TEXT, privateKey TEXT, token TEXT,employeeSnapId INTEGER,role INTEGER,userID INTEGER)");
        });
    return db;
  }
  Future<Null> clear()async{
    final db = await _localFile;
    db.execute("delete from user");
  }

  //保存数据
  Future<int> save(User user) async {
    final db = await _localFile;
    return db.transaction((trx) {
      return trx.rawInsert('INSERT INTO user(accountName,privateKey,token,employeeSnapId,role,userID)'
          ' VALUES("${user.accountName}","${user.privateKey}","${user.token}","${user.employeeSnapId}","${user.role}","${user.userID}")');
    });
  }

  //获取数据
  Future<List<Map>> get() async {
    final db = await _localFile;
    List<Map> list = await db.rawQuery('SELECT * FROM user');
    return list;
  }
}